package ServiceProvider;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class BroadcastSender {
	
	private static final String SEND_HINT = "Sent Message Successfully";
	MulticastSocket broadcastSocket;
	DatagramPacket dataPacket;
	InetAddress sendGroup;
	int sendPort;
	byte[] data = new byte[30];
	
	public BroadcastSender(String bcGroup, String port) {
		sendPort = convertPort(port);
		sendGroup = convertBroadcastGroup(bcGroup);
		
		try {
			broadcastSocket = new MulticastSocket(sendPort);
			broadcastSocket.joinGroup(sendGroup);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static int convertPort(String port) {
		return Integer.parseInt(port);
	}

	private static InetAddress convertBroadcastGroup(String broadcastGroup) {
		try {
			return InetAddress.getByName(broadcastGroup);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void broadcast(String message) {
		data = message.getBytes();
		dataPacket = new DatagramPacket(data, data.length, sendGroup, sendPort);
		
		try {
			broadcastSocket.send(dataPacket);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(SEND_HINT);
	}
}
